/*
 * UART.cpp
 *
 * Created: 2012-05-16 09:25:49
 *  Author: Johan
 */
#include "UART.h"
#define Debug false
	
UART::UART () {
	UBRR0L = 103;

	UCSR0B = 0b00011000;		//enable TX(Bit4 = 1), RX(Bit3 = 1)
	
	UCSR0C = 0b00000110;		//set frame format (8 bits, 1 stop bit)
}

void UART::send(const char* format, ...) {
	
	if(!Debug){
		return;
	}
	
	char buf[100];

	va_list ap;
	va_start(ap, format);
	vsprintf(buf,format,ap);
	va_end(ap);

	int lenght = strlen(buf);

	for (int i = 0; i < lenght; i++)
	{
		sendChar(buf[i]);
	}
}

void UART::send(int data) {
	char c[10];
	itoa(data, c, 10);
	
	send(c);
}

void UART::sendLn(const char* format, ...){
	
	char buf[100];
	va_list ap;
	va_start(ap, format);
	send(format,ap);
	va_end(ap);
	send("\n\r");
}

void UART::sendChar(char data) {
	while (!(UCSR0A & 0b00100000));
	UDR0 = data;
}

char UART::receive() {
	if (UCSR0A & 0b10000000) {
		return UDR0;
	}
	else
		return 0;
}
